<template>
  <div class="home-design-pro-layout">
    <!-- 左侧分组组件库 -->
    <div class="block-list-pro">
      <h3>组件库</h3>
      <div v-for="(group, gIdx) in blockGroups" :key="gIdx" class="block-group">
        <div class="group-title">{{ group.name }}</div>
        <draggable
          :list="group.blocks"
          :group="{ name: 'blocks', pull: 'clone', put: false }"
          :clone="cloneBlock"
          item-key="type"
          class="block-draggable-pro"
        >
          <template #item="{ element }">
            <div class="block-item-pro">
              <el-icon :size="18"><component :is="element.icon" /></el-icon>
              <span>{{ element.name }}</span>
            </div>
          </template>
        </draggable>
      </div>
    </div>
    <!-- 中间手机壳画布 -->
    <div class="canvas-area-pro">
      <div class="preview-mode-bar">
        <el-radio-group v-model="previewMode" size="small">
          <el-radio-button label="h5">H5预览</el-radio-button>
          <el-radio-button label="pc">PC预览</el-radio-button>
        </el-radio-group>
        <el-button type="primary" size="small" @click="saveDesign">保存</el-button>
        <el-button type="success" size="small" @click="publishDesign">发布</el-button>
      </div>
      <div :class="['phone-shell', previewMode]">
        <div class="phone-header"></div>
        <draggable
          v-model="canvasBlocks"
          :group="{ name: 'blocks', pull: true, put: true }"
          item-key="id"
          class="canvas-draggable-pro"
        >
          <template #item="{ element, index }">
            <vue3-draggable-resizable
              :x="element.x"
              :y="element.y"
              :w="element.w"
              :h="element.h"
              :active="selectedIndex === index"
              :parent="true"
              :min-width="40"
              :min-height="40"
              @activated="() => selectBlock(index)"
              @deactivated="() => selectBlock(-1)"
              @resizing="onResizing(index)"
              @dragging="onDragging(index)"
              :class="'canvas-block-pro block-'+element.type"
              :style="{
                background: element.style?.bgColor || '',
                borderRadius: (element.style?.radius || 8) + 'px',
                margin: (element.style?.marginY || 8) + 'px 0'
              }"
            >
              <div @click.stop="selectBlock(index)">
                <template v-if="element.type === 'banner'">
                  <el-carousel v-if="element.data.imgs && element.data.imgs.length" height="100%">
                    <el-carousel-item v-for="(img, idx) in element.data.imgs" :key="idx">
                      <el-image :src="img" style="width:100%;height:100%;object-fit:cover" />
                    </el-carousel-item>
                  </el-carousel>
                  <div v-else style="color:#bbb;text-align:center;line-height:100%;">未设置图片</div>
                </template>
                <template v-else-if="element.type === 'notice'">
                  <el-alert :title="element.data.text || '未设置公告内容'" type="info" show-icon />
                </template>
                <template v-else-if="element.type === 'product'">
                  <el-card shadow="never">
                    <div>{{ element.data.title || '商品推荐区' }}</div>
                    <div class="product-list-preview">
                      <div v-for="p in element.data.products" :key="p.id" class="product-item-preview">
                        <el-image :src="p.img" style="width:48px;height:48px;object-fit:cover;border-radius:6px;" />
                        <div class="product-info-preview">
                          <div class="product-name">{{ p.name }}</div>
                          <div class="product-price">¥{{ p.price }}</div>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </template>
                <template v-else-if="element.type === 'ad'">
                  <el-image v-if="element.data.img" :src="element.data.img" style="width:100%;height:100%;object-fit:cover" />
                  <div v-else style="color:#bbb;text-align:center;line-height:100%;">未设置广告图片</div>
                </template>
                <template v-else-if="element.type === 'quick-entry'">
                  <div class="quick-entry-block">
                    <el-button v-for="(entry, idx) in element.data.entries" :key="idx" size="small" style="margin:4px;">
                      <el-icon :size="16"><component :is="entry.icon || 'Promotion'" /></el-icon>
                      {{ entry.name || '入口' }}
                    </el-button>
                  </div>
                </template>
                <template v-else-if="element.type === 'activity'">
                  <el-card shadow="never">
                    <div>{{ element.data.title || '活动区块' }}</div>
                    <div class="activity-list-preview">
                      <div v-for="a in element.data.activities" :key="a.id" class="activity-item-preview">
                        <el-image :src="a.img" style="width:48px;height:48px;object-fit:cover;border-radius:6px;" />
                        <div class="activity-info-preview">
                          <div class="activity-title">{{ a.title }}</div>
                          <div class="activity-desc">{{ a.desc }}</div>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </template>
              </div>
              <div class="block-toolbar" v-if="selectedIndex === index">
                <el-button size="small" @click.stop="editBlock(element, index)">编辑</el-button>
                <el-button size="small" type="danger" @click.stop="removeBlock(index)">删除</el-button>
              </div>
            </vue3-draggable-resizable>
          </template>
        </draggable>
        <div v-if="canvasBlocks.length === 0" class="canvas-empty-pro">将组件拖拽到此处进行首页布局</div>
      </div>
    </div>
    <!-- 右侧属性面板 -->
    <div class="attr-panel-pro" @mousedown.stop>
      <h3>组件属性</h3>
      <div v-if="selectedBlock">
        <el-form label-width="80px">
          <template v-if="selectedBlock.type === 'banner'">
            <el-form-item label="轮播图片">
              <div v-for="(img, idx) in selectedBlock.data.imgs" :key="idx" style="display:flex;align-items:center;margin-bottom:8px;">
                <el-input v-model="selectedBlock.data.imgs[idx]" placeholder="请输入图片链接" style="flex:1;" />
                <el-button icon="el-icon-delete" @click="selectedBlock.data.imgs.splice(idx,1)" circle size="small" />
              </div>
              <el-button type="primary" size="small" @click="selectedBlock.data.imgs.push('')">添加图片</el-button>
            </el-form-item>
          </template>
          <template v-else-if="selectedBlock.type === 'ad'">
            <el-form-item label="图片URL">
              <el-input v-model="selectedBlock.data.img" placeholder="请输入图片链接" />
            </el-form-item>
          </template>
          <template v-else-if="selectedBlock.type === 'notice'">
            <el-form-item label="公告内容">
              <el-input v-model="selectedBlock.data.text" placeholder="请输入公告内容" />
            </el-form-item>
          </template>
          <template v-else-if="selectedBlock.type === 'product'">
            <el-form-item label="区块标题">
              <el-input v-model="selectedBlock.data.title" placeholder="如：热卖推荐" />
            </el-form-item>
            <el-form-item label="商品选择">
              <el-button @click="openProductDialog">选择商品</el-button>
              <div v-if="selectedBlock.data.products && selectedBlock.data.products.length" style="margin-top:8px;">
                <el-tag v-for="p in selectedBlock.data.products" :key="p.id" style="margin-right:4px;">{{ p.name }}</el-tag>
              </div>
            </el-form-item>
          </template>
          <template v-else-if="selectedBlock.type === 'quick-entry'">
            <el-form-item label="入口配置">
              <div v-for="(entry, idx) in selectedBlock.data.entries" :key="idx" style="display:flex;align-items:center;margin-bottom:8px;">
                <el-input v-model="entry.name" placeholder="入口名称" style="width:100px;" />
                <el-input v-model="entry.link" placeholder="跳转链接" style="flex:1;margin-left:8px;" />
                <el-button icon="el-icon-delete" @click="selectedBlock.data.entries.splice(idx,1)" circle size="small" />
              </div>
              <el-button type="primary" size="small" @click="selectedBlock.data.entries.push({ name: '', link: '' })">添加入口</el-button>
            </el-form-item>
          </template>
          <template v-else-if="selectedBlock.type === 'activity'">
            <el-form-item label="活动标题">
              <el-input v-model="selectedBlock.data.title" placeholder="如：限时秒杀" />
            </el-form-item>
            <el-form-item label="活动选择">
              <el-button @click="openActivityDialog">选择活动</el-button>
              <div v-if="selectedBlock.data.activities && selectedBlock.data.activities.length" style="margin-top:8px;">
                <el-tag v-for="a in selectedBlock.data.activities" :key="a.id" style="margin-right:4px;">{{ a.title }}</el-tag>
              </div>
            </el-form-item>
          </template>
          <el-form-item label="宽度">
            <el-input-number v-model="selectedBlock.w" :min="40" :max="320" />
          </el-form-item>
          <el-form-item label="高度">
            <el-input-number v-model="selectedBlock.h" :min="40" :max="600" />
          </el-form-item>
          <!-- 样式配置 -->
          <el-divider>区块样式</el-divider>
          <el-form-item label="背景色">
            <el-color-picker v-model="selectedBlock.style.bgColor" />
          </el-form-item>
          <el-form-item label="圆角">
            <el-input-number v-model="selectedBlock.style.radius" :min="0" :max="32" />
          </el-form-item>
          <el-form-item label="上下边距">
            <el-input-number v-model="selectedBlock.style.marginY" :min="0" :max="40" />
          </el-form-item>
        </el-form>
      </div>
      <div v-else style="color:#bbb;text-align:center;padding:40px 0;">请选择组件</div>
    </div>
    <!-- 区块编辑弹窗（可选，保留） -->
    <el-dialog v-model="editDialogVisible" title="编辑区块" width="400px">
      <template v-if="editingBlock">
        <div v-if="editingBlock.type === 'banner'">
          <el-form label-width="80px">
            <el-form-item label="轮播图片">
              <div v-for="(img, idx) in editingBlock.data.imgs" :key="idx" style="display:flex;align-items:center;margin-bottom:8px;">
                <el-input v-model="editingBlock.data.imgs[idx]" placeholder="请输入图片链接" style="flex:1;" />
                <el-button icon="el-icon-delete" @click="editingBlock.data.imgs.splice(idx,1)" circle size="small" />
              </div>
              <el-button type="primary" size="small" @click="editingBlock.data.imgs.push('')">添加图片</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div v-else-if="editingBlock.type === 'notice'">
          <el-form label-width="80px">
            <el-form-item label="公告内容">
              <el-input v-model="editingBlock.data.text" placeholder="请输入公告内容" />
            </el-form-item>
          </el-form>
        </div>
        <div v-else-if="editingBlock.type === 'product'">
          <el-form label-width="80px">
            <el-form-item label="区块标题">
              <el-input v-model="editingBlock.data.title" placeholder="如：热卖推荐" />
            </el-form-item>
          </el-form>
        </div>
        <div v-else-if="editingBlock.type === 'ad'">
          <el-form label-width="80px">
            <el-form-item label="图片URL">
              <el-input v-model="editingBlock.data.img" placeholder="请输入广告图片链接" />
            </el-form-item>
          </el-form>
        </div>
        <div v-else-if="editingBlock.type === 'quick-entry'">
          <el-form label-width="80px">
            <el-form-item label="入口配置">
              <div v-for="(entry, idx) in editingBlock.data.entries" :key="idx" style="display:flex;align-items:center;margin-bottom:8px;">
                <el-input v-model="entry.name" placeholder="入口名称" style="width:100px;" />
                <el-input v-model="entry.link" placeholder="跳转链接" style="flex:1;margin-left:8px;" />
                <el-button icon="el-icon-delete" @click="editingBlock.data.entries.splice(idx,1)" circle size="small" />
              </div>
              <el-button type="primary" size="small" @click="editingBlock.data.entries.push({ name: '', link: '' })">添加入口</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div v-else-if="editingBlock.type === 'activity'">
          <el-form label-width="80px">
            <el-form-item label="活动标题">
              <el-input v-model="editingBlock.data.title" placeholder="如：限时秒杀" />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBlockEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
  <!-- 商品选择弹窗 -->
  <el-dialog v-model="productDialog.value" title="选择商品" width="500px">
    <el-table :data="mockProducts" @selection-change="val => productSelect.value = val" :row-key="row => row.id" :default-selection="productSelect.value">
      <el-table-column type="selection" width="50" />
      <el-table-column prop="img" label="图片" width="60">
        <template #default="scope"><el-image :src="scope.row.img" style="width:40px;height:40px;object-fit:cover;" /></template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="price" label="价格" width="80" />
    </el-table>
    <template #footer>
      <el-button @click="productDialog.value = false">取消</el-button>
      <el-button type="primary" @click="confirmProductSelect">确定</el-button>
    </template>
  </el-dialog>
  <!-- 活动选择弹窗 -->
  <el-dialog v-model="activityDialog.value" title="选择活动" width="500px">
    <el-table :data="mockActivities" @selection-change="val => activitySelect.value = val" :row-key="row => row.id" :default-selection="activitySelect.value">
      <el-table-column type="selection" width="50" />
      <el-table-column prop="img" label="图片" width="60">
        <template #default="scope"><el-image :src="scope.row.img" style="width:40px;height:40px;object-fit:cover;" /></template>
      </el-table-column>
      <el-table-column prop="title" label="活动名称" />
      <el-table-column prop="desc" label="描述" />
    </el-table>
    <template #footer>
      <el-button @click="activityDialog.value = false">取消</el-button>
      <el-button type="primary" @click="confirmActivitySelect">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, shallowRef, computed } from 'vue'
import draggable from 'vuedraggable'
import Vue3DraggableResizable from 'vue3-draggable-resizable'
import 'vue3-draggable-resizable/dist/Vue3DraggableResizable.css'
import { Picture, Bell, GoodsFilled, Promotion, Box, DataLine } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 丰富区块库
const blockGroups = [
  {
    name: '基础区块',
    blocks: [
      { type: 'banner', name: '轮播图', icon: Picture },
      { type: 'notice', name: '公告栏', icon: Bell },
      { type: 'product', name: '商品推荐', icon: GoodsFilled },
      { type: 'ad', name: '广告位', icon: Promotion },
      { type: 'quick-entry', name: '快捷入口', icon: Box },
      { type: 'activity', name: '活动区块', icon: DataLine }
    ]
  }
]
const previewMode = ref('h5')
function saveDesign() {
  ElMessage.success('保存成功（mock）')
}
function publishDesign() {
  ElMessage.success('发布成功（mock）')
}

const canvasBlocks = ref<any[]>([])
const selectedIndex = ref(-1)
const selectedBlock = computed(() => canvasBlocks.value[selectedIndex.value] || null)

// mock商品和活动数据
const mockProducts = [
  { id: 1, name: 'iPhone 15 Pro', img: 'https://img.example.com/iphone.jpg', price: 8999 },
  { id: 2, name: '小米14', img: 'https://img.example.com/xiaomi.jpg', price: 3999 },
  { id: 3, name: 'AirPods Pro', img: 'https://img.example.com/airpods.jpg', price: 1999 }
]
const mockActivities = [
  { id: 1, title: '618大促', desc: '全场满减', img: 'https://img.example.com/618.jpg' },
  { id: 2, title: '会员日', desc: '专属福利', img: 'https://img.example.com/vip.jpg' }
]
// 商品选择弹窗
const productDialog = ref(false)
const productSelect = ref<any[]>([])
function openProductDialog() {
  productSelect.value = selectedBlock.value?.data.products || []
  productDialog.value = true
}
function confirmProductSelect() {
  if (selectedBlock.value) selectedBlock.value.data.products = [...productSelect.value]
  productDialog.value = false
}
// 活动选择弹窗
const activityDialog = ref(false)
const activitySelect = ref<any[]>([])
function openActivityDialog() {
  activitySelect.value = selectedBlock.value?.data.activities || []
  activityDialog.value = true
}
function confirmActivitySelect() {
  if (selectedBlock.value) selectedBlock.value.data.activities = [...activitySelect.value]
  activityDialog.value = false
}

function cloneBlock(block: any) {
  return {
    id: Date.now() + Math.random(),
    type: block.type,
    data:
      block.type === 'banner' ? { imgs: [] } :
      block.type === 'quick-entry' ? { entries: [] } :
      block.type === 'product' ? { title: '', products: [] } :
      block.type === 'activity' ? { title: '', activities: [] } :
      {},
    x: 10,
    y: 10 + canvasBlocks.value.length * 60,
    w: 300,
    h: 80,
    style: { bgColor: '', radius: 8, marginY: 8 }
  }
}
function getBlockName(type: string) {
  for (const group of blockGroups) {
    const found = group.blocks.find(b => b.type === type)
    if (found) return found.name
  }
  return type
}
function selectBlock(idx: number) {
  selectedIndex.value = idx
}
function updateBlockSize(idx: number, x: number, y: number, w: number, h: number) {
  const block = canvasBlocks.value[idx]
  if (block) {
    block.x = x; block.y = y; block.w = w; block.h = h
  }
}
function updateBlockPos(idx: number, x: number, y: number) {
  const block = canvasBlocks.value[idx]
  if (block) {
    block.x = x; block.y = y
  }
}
function onResizing(idx: number) {
  return (_: any, pos: { x: number; y: number; w: number; h: number }) => {
    updateBlockSize(idx, pos.x, pos.y, pos.w, pos.h)
  }
}
function onDragging(idx: number) {
  return (_: any, pos: { x: number; y: number }) => {
    updateBlockPos(idx, pos.x, pos.y)
  }
}
// 编辑区块弹窗（可选）
const editDialogVisible = ref(false)
const editingBlock = shallowRef<any>(null)
let editingIndex = -1
function editBlock(block: any, index: number) {
  editingBlock.value = JSON.parse(JSON.stringify(block))
  editingIndex = index
  editDialogVisible.value = true
}
function saveBlockEdit() {
  if (editingIndex > -1 && editingBlock.value) {
    canvasBlocks.value[editingIndex] = JSON.parse(JSON.stringify(editingBlock.value))
  }
  editDialogVisible.value = false
  editingIndex = -1
}
function removeBlock(index: number) {
  canvasBlocks.value.splice(index, 1)
  if (selectedIndex.value === index) selectedIndex.value = -1
}
</script>

<style scoped>
.home-design-pro-layout {
  display: flex;
  gap: 16px;
  padding: 20px;
  min-height: 600px;
  background: #f5f6fa;
}
.block-list-pro {
  width: 180px;
  background: #fff;
  border-radius: 8px;
  padding: 16px 8px;
  box-shadow: 0 1px 4px 0 rgba(0,0,0,0.03);
  height: fit-content;
}
.block-list-pro h3 {
  font-size: 16px;
  margin-bottom: 12px;
}
.block-group {
  margin-bottom: 18px;
}
.group-title {
  font-size: 14px;
  color: #888;
  margin-bottom: 6px;
  padding-left: 4px;
}
.block-draggable-pro {
  min-height: 40px;
}
.block-item-pro {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 10px;
  cursor: grab;
  border: 1px solid #f0f0f0;
  transition: box-shadow .2s;
}
.block-item-pro:active {
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.08);
}
.canvas-area-pro {
  flex: 1;
  min-width: 340px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}
.preview-mode-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 0 10px;
}
.phone-shell {
  width: 340px;
  height: 700px;
  background: #fff;
  border-radius: 32px;
  box-shadow: 0 2px 16px 0 rgba(0,0,0,0.08);
  position: relative;
  overflow: hidden;
  padding: 24px 10px 10px 10px;
  display: flex;
  flex-direction: column;
}
.phone-shell.h5 {
  width: 340px;
  height: 700px;
  background: #fff;
  border-radius: 32px;
  box-shadow: 0 2px 16px 0 rgba(0,0,0,0.08);
  position: relative;
  overflow: hidden;
  padding: 24px 10px 10px 10px;
  display: flex;
  flex-direction: column;
}
.phone-shell.pc {
  width: 340px;
  height: 700px;
  background: #fff;
  border-radius: 32px;
  box-shadow: 0 2px 16px 0 rgba(0,0,0,0.08);
  position: relative;
  overflow: hidden;
  padding: 24px 10px 10px 10px;
  display: flex;
  flex-direction: column;
}
.phone-header {
  height: 24px;
  background: #f5f6fa;
  border-radius: 16px 16px 0 0;
  margin-bottom: 8px;
}
.canvas-draggable-pro {
  flex: 1;
  min-height: 120px;
  position: relative;
}
.canvas-block-pro {
  position: absolute;
  box-sizing: border-box;
  border: 2px solid transparent;
  background: #f8f9fa;
  border-radius: 6px;
  z-index: 1;
}
.canvas-block-pro:deep(.vdr.active) {
  border-color: #409eff;
  z-index: 2;
}
.block-toolbar {
  position: absolute;
  top: 2px;
  right: 2px;
  z-index: 10;
  display: flex;
  gap: 4px;
}
.block-content {
  min-height: 40px;
  width: 100%;
  height: 100%;
}
.canvas-empty-pro {
  color: #bbb;
  text-align: center;
  padding: 40px 0;
}
.attr-panel-pro {
  width: 260px;
  background: #fff;
  border-radius: 8px;
  padding: 16px 16px 0 16px;
  box-shadow: 0 1px 4px 0 rgba(0,0,0,0.03);
  min-height: 400px;
}
.attr-panel-pro h3 {
  font-size: 16px;
  margin-bottom: 12px;
}
.quick-entry-block {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px 0;
}
.product-list-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}
.product-item-preview {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 6px;
  padding: 4px 8px;
  margin-bottom: 4px;
}
.product-info-preview {
  margin-left: 8px;
}
.product-name {
  font-size: 14px;
  font-weight: 500;
}
.product-price {
  font-size: 13px;
  color: #f56c6c;
}
.activity-list-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}
.activity-item-preview {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 6px;
  padding: 4px 8px;
  margin-bottom: 4px;
}
.activity-info-preview {
  margin-left: 8px;
}
.activity-title {
  font-size: 14px;
  font-weight: 500;
}
.activity-desc {
  font-size: 13px;
  color: #888;
}
</style> 